<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item label="挂号状态" prop="registerStatus">
        <el-select
          v-model="formData.registerStatus"
          placeholder="请选择挂号状态"
          clearable
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MEDICAL_REGISTER_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">
        确 定
      </el-button>
      <el-button @click="dialogVisible = false">
        取 消
      </el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict';
import * as RegisterApi from '@/api/medical/register';
import { FormRules } from 'element-plus';
import { defineOptions, defineExpose, ref, reactive } from 'vue';
import { useMessage } from '@/hooks/web/useMessage';
import { useI18n } from 'vue-i18n';

defineOptions({ name: 'RegisterStatusForm' });

const { t } = useI18n();
const message = useMessage();

const dialogVisible = ref(false);
const dialogTitle = ref('');
const formLoading = ref(false);
const formType = ref('');
const formData = ref({
  registerStatus: undefined,
  id: undefined,
});
const formRules = reactive<FormRules>({
  registerStatus: [{ required: true, message: '请选择挂号状态' }],
});
const formRef = ref();

const open = async (type: string, id: number, currentStatus: number) => {
  dialogVisible.value = true;
  dialogTitle.value = t('action.' + type);
  formType.value = type;
  formData.value.id = id;
  formData.value.registerStatus = currentStatus;
  resetForm();
};

defineExpose({ open });

const emit = defineEmits(['success']);
const submitForm = async () => {
  if (!formRef) return;
  const valid = await formRef.value.validate();
  if (!valid) return;
  formLoading.value = true;
  try {
    const data = formData.value as unknown as RegisterApi.MRegisterVO;
    await RegisterApi.updateRegisterStatus(data.id, data.registerStatus);
    message.success(t('common.updateSuccess'));
    dialogVisible.value = false;
    emit('success');
  } finally {
    formLoading.value = false;
  }
};

const resetForm = () => {
  formData.value = {
    registerStatus: undefined,
    id: undefined,
  };
  formRef.value?.resetFields();
};
</script>